import {
  getUserServiceAddress
} from "../../assets/js/serviceAddress.js";
import {
  getUserpatientsList
} from "../../assets/js/servicePatient.js";
import {
  apiSaveOrder,
  apiGetDetail,
  apiGetServiceTime
} from "../../http/server.js"
import axios from "../../http/axios.js"
import {
  oneDateGetNextSevenDate,
  formatTime
} from "../../utils/util.js"
import {
  res2data
} from "../../assets/js/serviceTime.js"
import {
  pay
} from "../../assets/js/pay.js"

Page({
  data: {
    noList: {
      img: "/assets/img/nojjlxr.png",
      text: "您还没有可用服务地址~"
    },
    banner: {
      background: ['https://leaninnurse.oss-cn-hangzhou.aliyuncs.com/blog/2019-11-26/6e89a019406d44f9aff74a17d65c7feb-8.png'],
      indicatorDots: false,
      vertical: false,
      autoplay: true,
      interval: 2500,
      duration: 500,
    },
    type: 1, // 服务类型 1 上门 2 院内
    selectIndex: 0, //选择各项时弹出哪一项的索引
    patientList: [
      // {
      //   name: "张三",
      //   sex: "男",
      //   relationship: "朋友"
      // },
      // {
      //   name: "李四",
      //   sex: "女",
      //   relationship: "父母"
      // },
    ], //选择服务患者的数据
    timeContent: [{
        title: {
          active: true, // true选择中的状态,false未选择中的状态
          titleTime: "星期一 (2019/04/02)"
        },
        allTime: [{
            timeOne: "3:00 上门",
            state: 1 // 1为未选择但是可以选择的，2为已选择， 3为未选择但是不可以进行选择
          },
          {
            timeOne: "4:00 上门",
            state: 1
          },
          {
            timeOne: "5:00 上门",
            state: 3
          },
          {
            timeOne: "5:00 上门",
            state: 1
          },
          {
            timeOne: "5:00 上门",
            state: 3
          }
        ]
      },
      {
        title: {
          active: false, // true选择中的状态,false未选择中的状态
          titleTime: "星期二 (2019/04/02)"
        },
        allTime: [{
          timeOne: "3:00 上门",
          state: 1
        }]
      },
      {
        title: {
          active: true, // true选择中的状态,false未选择中的状态
          titleTime: "星期一 (2019/04/02)"
        },
        allTime: [{
            timeOne: "3:00 上门",
            state: 1 // 1为未选择但是可以选择的，2为已选择， 3为未选择但是不可以进行选择
          },
          {
            timeOne: "4:00 上门",
            state: 1
          },
          {
            timeOne: "5:00 上门",
            state: 3
          },
          {
            timeOne: "5:00 上门",
            state: 1
          },
          {
            timeOne: "5:00 上门",
            state: 3
          }
        ]
      },
      {
        title: {
          active: true, // true选择中的状态,false未选择中的状态
          titleTime: "星期一 (2019/04/02)"
        },
        allTime: [{
            timeOne: "3:00 上门",
            state: 1 // 1为未选择但是可以选择的，2为已选择， 3为未选择但是不可以进行选择
          },
          {
            timeOne: "4:00 上门",
            state: 1
          },
          {
            timeOne: "5:00 上门",
            state: 3
          },
          {
            timeOne: "5:00 上门",
            state: 1
          },
          {
            timeOne: "5:00 上门",
            state: 3
          }
        ]
      },
    ], // 选择服务时间的数据
    addressList: [
      // {
      //   name: "浙江省杭州市滨江区",
      //   sex: "钱江春晓10号楼508室"
      // },
      // {
      //   name: "浙江省杭州市滨江区",
      //   sex: "钱江春晓10号楼501室"
      // }
    ], // 选择服务地址的数据格式
    van_popupShow: false, // 弹出层的显示隐藏
    selectConsumablesObj: {
      // idIndex: 0, // list索引 0表示索引不需要耗材 1表示索引选择耗材
      // list: [{
      //     id: 1,
      //     content: "耗材包 | ￥10"
      //   },
      //   {
      //     id: 2,
      //     content: "不需要耗材"
      //   }
      // ],
      // detail: "耗材详情：无菌棉签×1、无菌注射器×1、纱布块×1、消毒液×1",
      // number: 1
    }, // 选择耗材的数据格式
    serviceDetails: [
      // {
      //   title: "服务提示",
      //   list: [
      //     "用户需要1",
      //     "用户需要2"
      //   ]
      // },
      // {
      //   title: "温馨提醒",
      //   list: [
      //     "用户需要1",
      //     "用户需要2"
      //   ]
      // },
      // {
      //   title: "服务说明",
      //   list: [
      //     "用户需要1",
      //     "用户需要2"
      //   ]
      // }
    ],
    selectList: [{
        isNeedConsumables: 0, // 是否需要耗材 0 不需要 1 需要
        key: "耗材",
        value: "",
        selectNmae: "选择耗材"
      },
      {
        key: "服务地址",
        value: "",
        selectNmae: "选择地址"
      },
      {
        key: "服务时间",
        value: "",
        selectNmae: "选择时间"
      },
      {
        key: "服务患者",
        value: "",
        selectNmae: "选择患者"
      }
    ], // 选择各项的数组
    introduce: {
      // title: "浙江省第一人民医院打针服务",
      // seviceType: [{
      //     id: 1,
      //     value: "上门服务"
      //   },
      //   {
      //     id: 2,
      //     value: "不含耗材诶"
      //   },
      //   {
      //     id: 2,
      //     value: "不含耗材诶"
      //   }
      // ],
      // price: "200",
      // description: "执业护士上门提供皮下及肌肉注射技术服务"
    }, // 最上边的介绍部分
    serviceId: "", // 服务唯一标识
    hospitalId: "", // 医院唯一标识
  },

  onLoad: function(options) {
    let title = options.title; // 设置头部导航标题
    let serviceId = options.serviceId; // 选中服务的唯一标识
    let hospitalId = options.hospitalId; // 选中医院的唯一标识
    wx.setNavigationBarTitle({
      title: title,
    })
    this.setData({
      serviceId: serviceId,
      hospitalId: hospitalId,
    })
    this.getServiceDetail();
  },

  onReady: function() {},

  onShow: function() {
    this.getpatientList();
    this.getAddressList();
    this.getServiceTime();
  },

  // 获取详情
  getServiceDetail() {
    axios({
      url: apiGetDetail,
      data: {
        id: this.data.serviceId
      }
    }).then(res => {
      // console.log(res);
      let seviceType = [{
          id: 1,
          value: Number(res.serviceItems.type) === 1 ? "上门服务" : "院内服务"
        },
        {
          id: 2,
          value: Number(res.serviceItems.isConsumables) === 1 ? "不含耗材包" : "含耗材包"
        }
      ];
      let banner = {
        background: res.serviceItems.banner.split("、"),
        indicatorDots: false,
        vertical: false,
        autoplay: true,
        interval: 2500,
        duration: 500,
      }
      let introduce = {
        title: res.serviceItems.name,
        price: Number(res.serviceItems.servicePrice) / 100,
        description: res.serviceItems.introduce,
        seviceType,
      }
      let serviceDetails = [{
          title: "服务提示",
          list: res.serviceItems.serviceTips.split("、")
        },
        {
          title: "温馨提醒",
          list: res.serviceItems.serviceRemind.split("、")
        },
        {
          title: "服务说明",
          list: res.serviceItems.serviceExplain.split("、")
        }
      ];
      let detail = "耗材详情：";
      res.consumablesList.forEach(item => {
        detail += `${item.name}×${item.num}、`
      })
      detail = detail.slice(0, detail.length - 1);
      let selectConsumablesObj = {
        price: Number(res.serviceItems.consumablesPrice) / 100,
        idIndex: 0, // list索引  0表示索引不需要耗材 1表示索引选择耗材
        list: [{
            id: 1,
            content: `耗材包 | ￥${Number(res.serviceItems.consumablesPrice)/100}`
          },
          {
            id: 2,
            content: "不需要耗材"
          }
        ],
        detail,
        number: 1
      }
      let selectList = [{
          isNeedConsumables: 1, // 默认 1需要耗材
          key: "耗材",
          value: "",
          selectNmae: "选择耗材"
        },
        {
          key: "服务地址",
          value: "",
          selectNmae: "选择地址"
        },
        {
          key: "服务时间",
          value: "",
          selectNmae: "选择时间"
        },
        {
          key: "服务患者",
          value: "",
          selectNmae: "选择患者"
        }
      ]
      if (Number(res.serviceItems.isConsumables) === 0) {
        selectList[0].isNeedConsumables = 0;
        selectList[0].value = "无需购买耗材包";
      }
      this.setData({
        banner,
        introduce,
        serviceDetails,
        selectConsumablesObj,
        type: res.serviceItems.type,
        selectList
      });
    })
  },
  checkSelect() {
    let {
      selectList
    } = this.data;
    if (!selectList[0].value) {
      wx.showToast({
        title: "请选择耗材后再下单",
        icon: "none"
      })
      return false;
    }
    if (!selectList[1].value) {
      wx.showToast({
        title: "请选择服务地址后再下单",
        icon: "none"
      })
      return false;
    }
    if (!selectList[2].value) {
      wx.showToast({
        title: "请选择服务时间后再下单",
        icon: "none"
      })
      return false;
    }
    if (!selectList[3].value) {
      wx.showToast({
        title: "请选择服务患者后再下单",
        icon: "none"
      })
      return false;
    }
    return true;
  },
  // 立即预约
  clickMakeAppointment: function() {
    let userInfo = wx.getStorageSync("userInfo");
    if (!(userInfo && userInfo.userName && userInfo.idCard)) {
      wx.showToast({
        title: "请您实名认证后再下单",
        icon: "none"
      })
      setTimeout(() => {
        wx.navigateTo({
          url: "/pages/u_realNameAuthentication/u_realNameAuthentication",
        })
      }, 1500)
      return;
    }
    if (!this.checkSelect()) return;
    let {
      introduce,
      selectConsumablesObj,
      selectList,
      type,
      serviceId,
      hospitalId
    } = this.data;
    let consumablesNum;
    let data = {
      consumablesName: selectList[0].value === "不需要耗材" || selectList[0].value === "无需购买耗材包" ? "无耗材" : selectConsumablesObj.detail.slice(5, selectConsumablesObj.detail.length), // 耗材包名字拼接
      consumablesNum: selectList[0].value === "不需要耗材" || selectList[0].value === "无需购买耗材包" ? 0 : selectConsumablesObj.number, // 耗材包数量
      serviceTime: formatTime(new Date(selectList[2].value.slice(0, 15))).replace(/\//g, "-"), // 服务时间      
      serviceAddress: selectList[1].value, // 服务地址
      userId: wx.getStorageSync("userInfo").userId, // 用户
      patientId: selectList[3].patientId, // 病人
      serviceId: serviceId, // 服务ID
      hospitalId: hospitalId // 服务医院
    }
    // console.log(data);
    // return;
    // 下单
    axios({
      url: apiSaveOrder,
      method: "POST",
      data: data,
    }).then(res => {
      // console.log("382", res);
      return pay({
        orderNo: res.orderNo
      })
    }).then(res => {
      wx.showToast({
        title: "支付成功",
        icon: "none",
      })
      // 成功设置跳转到待服务
      wx.setStorageSync("tabIdIndex", "2")
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/u_order/u_order'
        })
      }, 1500)
    }).catch(err => {
      wx.showToast({
        title: "支付失败",
        icon: "none",
      })
      wx.setStorageSync("tabIdIndex", "1")
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/u_order/u_order'
        })
      }, 1500)
    })
  },
  /**
   * 服务患者的选择
   */
  // 获取服务患者
  getpatientList: function() {
    getUserpatientsList().then(patientList => {
      this.setData({
        patientList
      })
    })
  },
  // 选择一个服务患者
  clickPatientSuccess: function(e) {
    let obj = e.detail;
    let selectList = this.data.selectList;
    selectList[3].value = obj.item.name;
    selectList[3].patientId = obj.item.patientId;
    selectList[3].userId = obj.item.userId;
    this.setData({
      van_popupShow: false,
      selectList
    })
  },
  // 添加服务患者
  addPatients: function() {
    wx.navigateTo({
      url: "/pages/u_updateServicePatients/u_updateServicePatients?type=add",
    })
  },
  // 编辑服务患者
  editPatients: function(e) {
    wx.navigateTo({
      url: `/pages/u_updateServicePatients/u_updateServicePatients?type=edit&patientId=${e.detail.patientId}`,
    })
  },
  /**
   * 服务时间的选择
   */
  // 服务时间点击完成
  clickTimeSuccess: function() {
    let timeContent = this.data.timeContent;
    let state = 1;
    let str = ""; // 选择定的时间
    let selectList = this.data.selectList;
    timeContent.forEach((item, index) => {
      item.allTime.forEach((item1, index1) => {
        if (item1.state == 2) {
          str = item.title.titleTime.slice(5, 15) + " " + item1.timeOne;
          selectList[2].value = str;
        } else {}
      })
    });
    this.setData({
      van_popupShow: false,
      selectList: selectList
    })
  },
  // 获取服务时间
  getServiceTime: function() {
    let type = this.data.type; // 排班性质 1上门 2院内
    let data = {
      hospitalId: this.data.hospitalId,
      type,
      startTime: oneDateGetNextSevenDate().date,
      endTime: oneDateGetNextSevenDate().nextDate
    }
    axios({
      url: apiGetServiceTime,
      data: data
    }).then(res => {
      // console.log("370", res);
      let timeContent = res2data(res);
      this.setData({
        // timeContent
      })
    })
  },
  // 选择某一个时间
  hanleClickTimeOne: function(e) {
    let obj = e.detail;
    let item = obj.item;
    let index = obj.index;
    let item1 = obj.item1;
    let index1 = obj.index1;
    let timeContent = this.data.timeContent;
    if (item1.state == 3) {
      wx.showToast({
        title: "该时间没有服务排班,请您选择其他服务时间",
        icon: "none"
      })
      return;
    } else if (item1.state == 2) {
      return;
    } else {
      timeContent.forEach((timeItem, timeIndex) => {
        if (timeIndex == index) {
          timeItem.allTime.forEach((timeItem1, timeIndex1) => {
            if (timeIndex1 == index1) {
              if (timeItem1.state == 1) {
                timeItem1.state = 2;
              } else if (timeItem1.state == 2) {

              } else {
                wx.showToast({
                  title: "该服务时间预约人数已经达到上限,请您选择其他服务时间吧！",
                  icon: "none"
                })
              }
            } else {
              if (timeItem1.state == 1) {

              } else if (timeItem1.state == 2) {
                timeItem1.state = 1;
              } else {

              }
            }
          })
        } else {
          timeItem.title.active = false;
          timeItem.allTime.forEach((timeItem1, timeIndex1) => {
            if (timeItem1.state == 1) {

            } else if (timeItem1.state == 2) {
              timeItem1.state = 1;
            } else {

            }
          })
        }
      })
    }
    this.setData({
      timeContent
    })
  },
  // 点击切换总体的时间
  handleClickSwitch: function(e) {
    let obj = e.detail;
    let index = obj.index;
    let timeContent = this.data.timeContent;
    timeContent.forEach((item1, index1) => {
      if (index1 == index) {
        item1.title.active = !item1.title.active;
      }
    });
    this.setData({
      timeContent: timeContent
    })
  },
  /**
   * 服务地址的事件处理
   */
  // 获取服务地址
  getAddressList: function() {
    getUserServiceAddress().then(list => {
      this.setData({
        addressList: list,

      })
    })
  },
  // 编辑服务地址
  editContacts: function(e) {
    wx.navigateTo({
      url: `/pages/u_updateServiceAddress/u_updateServiceAddress?type=edit&item=${JSON.stringify(e.detail)}`,
    })
  },
  // 添加服务地址
  addContacts: function() {
    wx.navigateTo({
      url: "/pages/u_updateServiceAddress/u_updateServiceAddress?type=add",
    })
  },
  // 选择其中的一项地址
  clickAddress: function(e) {
    let obj = e.detail;
    let item = obj.item;
    let str = item.name + item.sex;
    let selectList = this.data.selectList;
    selectList[1].value = str;
    this.setData({
      van_popupShow: false,
      selectList: selectList
    })
  },
  // 点击蒙版弹出层消失
  onClose: function() {
    this.setData({
      van_popupShow: false
    })
  },
  /**
   * 选择耗材弹出来的事件
   */
  handleClickSelectConsumables: function(e) {
    let obj = e.detail;
    let item = obj.item;
    let index = obj.index;
    let selectConsumablesObj = this.data.selectConsumablesObj;
    selectConsumablesObj.idIndex = index;
    this.setData({
      selectConsumablesObj
    })
  },
  // 增加数量
  handleClickAddNumber: function() {
    let selectConsumablesObj = this.data.selectConsumablesObj;
    if (selectConsumablesObj.idIndex == 1) { //表示不需要选择耗材
      wx.showToast({
        title: "请选择耗材包",
        icon: "none"
      })
      return;
    } else {
      selectConsumablesObj.number++;
    }
    this.setData({
      selectConsumablesObj: selectConsumablesObj
    })
  },
  // 减少耗材数量
  handleClickReduceNumber: function() {
    let selectConsumablesObj = this.data.selectConsumablesObj;
    if (selectConsumablesObj.idIndex == 1) { //表示不需要选择耗材
      wx.showToast({
        title: "请选择耗材包",
        icon: "none"
      })
      return;
    } else {
      if (selectConsumablesObj.number > 1) {
        selectConsumablesObj.number--;
      }
    }
    this.setData({
      selectConsumablesObj: selectConsumablesObj
    })
  },
  // 选择耗材包的完成
  clickConsumablesSuccess: function() {
    let selectConsumablesObj = this.data.selectConsumablesObj;
    let selectList = this.data.selectList;
    selectList[0].value = selectConsumablesObj.idIndex == 0 ? `耗材包 x ${selectConsumablesObj.number}` : "不需要耗材";
    this.setData({
      selectList: selectList,
      van_popupShow: false
    })
  },
  // 选择各项的操作
  handleClickSelect: function(e) {
    let dataset = e.currentTarget.dataset;
    let item = dataset.item;
    let index = dataset.index;
    switch (index) {
      case 0:
        { // 选择耗材
          // 0 确定不需要耗材阻断后续执行
          if (!this.data.selectList[0].isNeedConsumables) {
            wx.showToast({
              title: "无需购买耗材包",
              icon: "none"
            })
            return;
          }
          this.setData({
            van_popupShow: true,
            selectIndex: 0
          })
          break;
        }
      case 1:
        { // 选择服务地址
          this.setData({
            van_popupShow: true,
            selectIndex: 1,
            noList: {
              img: "/assets/img/nojjlxr.png",
              text: "您还没有可用服务地址~"
            }
          })
          break;
        }
      case 2:
        { // 选择服务时间
          this.setData({
            van_popupShow: true,
            selectIndex: 2,
            noList: {
              img: "/assets/img/nojjlxr.png",
              text: "当前医院暂未给该服务进行排班，您稍后~"
            }
          })
          break;
        }
      case 3:
        { // 选择服务患者
          this.setData({
            van_popupShow: true,
            selectIndex: 3,
            noList: {
              img: "/assets/img/nofwhz.png",
              text: "您还没有可选服务患者~"
            }
          })
          break;
        }
    }
  }
})